import {useSystemStore} from '@/stores/system.js';

const $store = useSystemStore();
const phoneReg = /^1\d{10}$/;
const mailReg=/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
const idCardReg=/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/
const pwdReg = /^[0-9A-Za-z]{6,20}$/;
const host='https://yunapi.dongleezy.com';
const loginReback={
	url:'/pages/index/index',
	isShow:false
};
// 检查是否是电话号码
const isPhone = number => {
	return phoneReg.test(number)
};

const isEmail=mail=>{
	return mailReg.test(mail)
}
const pwdIsOk=pwd=>{
	return pwdReg.test(pwd);
}
const emptyFun = () => {}
// 函数参数必须是字符串，因为二代身份证号码是十八位，而在javascript中，十八位的数值会超出计算范围，造成不精确的结果，导致最后两位和计算的值不一致，从而该函数出现错误。
// 详情查看javascript的数值范围
const checkIDCard=idcode=>{
   return idCardReg.test(idcode)
}
const noEmpty=(val)=>{
	if(val===0) return true;
	return !!val
}

const isHKCard=card=>{
  // 港澳居民来往内地通行证
  // 规则： H/M + 10位或6位数字
  // 样本： H1234567890
  var reg = /^([A-Z]\d{6,10}(\(\w{1}\))?)$/;
  return reg.test(card)
 //  if (reg.test(card) === false) {
	// return { 'status': 0, 'msg': '港澳居民来往内地通行证号码不合规' };
 //  } else {
	// return { 'status': 1, 'msg': '校验通过' };
 //  }
};
const isPassPortCard=card=>{
  // 护照
  // 规则： 14/15开头 + 7位数字, G + 8位数字, P + 7位数字, S/D + 7或8位数字,等
  // 样本： 141234567, G12345678, P1234567
  var reg = /^([a-zA-z]|[0-9]){5,17}$/;
  return reg.test(card);
 //  if (reg.test(card) === false) {
	// return { 'status': 0, 'msg': '护照号码不合规' };
 //  } else {
	// return { 'status': 1, 'msg': '校验通过' };
 //  }
}
	
const checkFn={
	isPhone,
	checkIDCard,
	isEmail,
	noEmpty,
	isHKCard,
	isPassPortCard,
	pwdIsOk
};

const prePage = (num=2)=>{
	let pages = getCurrentPages();
	let prePage = pages[pages.length - num];
	// #ifdef H5
	return prePage;
	// #endif
	return prePage.$vm;
}
const refreshPrePage=(fn='refreshPage',num)=>{
	let page=prePage(num);
	page[fn]&&page[fn]();
}
const refreshAndReback=(fn)=>{
	refreshPrePage(fn)
	uni.navigateBack({
		animationDuration:1500
	})
}
const showToast = (title, {cb = null,duration = 3000,icon = 'none'} = {}) => {
	uni.showToast({
		title,
		icon,
		duration,
	});
	if (typeof(cb) === 'function') {
		setTimeout(() => cb(), duration);
	}
}

const showDialog = (msg, {
	title = "提示",
	showCancel = false,
	cancelText = "取消",
	confirmText = "确定",
	confirmColor = $store.seMain.value,
	ok_cb = emptyFun,
	no_cb = emptyFun
} = {}) => {
	uni.showModal({
		title: title,
		content: msg,
		showCancel,
		cancelText,
		cancelColor: '#333333',
		confirmText,
		confirmColor,
		success(res) {
			if (res.confirm) {
				ok_cb();
			} else if (res.cancel) {
				no_cb()
			}
		}
	})
}
const rejectToLogin=(msg='请先登录')=>{
	// let pages = getCurrentPages();
	// let currentPage = pages[pages.length - 1];
	let currentUrl='';
	// if(currentPage){
	// 	currentUrl=currentPage.$page.fullPath;
	// }else{
		currentUrl=loginReback.url;
	// }
	toLogin(currentUrl,{isShowDialog:true,msg});
}
const getAjaxHeader=(needToken,header={})=>{
	return new Promise((resolve,reject)=>{
		if(needToken){
			let token=$store.token.value;
			if(!token){
				rejectToLogin();
				reject()
			}else{
				header.Authorization='dl'+token;
				resolve(header)
			}
		}else{
			resolve(header)
		}
	})
}
const requestBack=(data,needCode=false)=>{
	return new Promise((resolve, reject) => {
		// process.env.NODE_ENV=='development'&&console.log(data)
		if(typeof(data)=='string'){
			data=JSON.parse(data);
		}
		if (data.code == 200) {
			resolve(data);
		}
		else if(data.code == 401 || data.code==403){
			rejectToLogin('登录超时，请重新登录');
			reject('请先登录')
		}
		else if(data.status == 500){
			rejectToLogin('登录超时，请重新登录');
			reject('请先登录')
		}
		else {
			if((data.msg||'').indexOf('成功')!=-1){
				resolve(data)
			}else{
				reject(needCode?data:data.msg);
			}
		}
	})
}
const ajax = (url, param = {}, method = 'POST',needToken=true, needLoading = true , needCode=false,json=false) => {
	return new Promise((resolve, reject) => {
		needLoading && uni.showLoading({
			title: "请求发送中...",
			mask: true
		});
		if(!/^https?:\/\//.test(url)){
			url=host + url
		}
		getAjaxHeader(needToken,{'content-type': `application/${json?'json':'x-www-form-urlencoded'}`}).then(header=>{
			uni.request({
				url,
				method: method,
				data: param,
				header,
				success(res) {
					// process.env.NODE_ENV=='development'&&console.log(url,param)
					requestBack(res.data,needCode).then(data=>{
						resolve(data.data||data||{})
					},reject)
				},
				fail(err) {
					// console.log(url,err)
					showToast(err)
					reject((err&&err.msg)||"ajaxError");
				},
				complete() {
					needLoading && uni.hideLoading();
				}
			})
		},err=> {
			needLoading && uni.hideLoading();
		})
	});
}
const ajaxGet=(url, params={})=>{
	let {data={},method='GET',needToken=true,needLoading=true,needCode=false,json=false}=params;
	return ajax (url, data,method,needToken, needLoading, needCode,json)
}
const ajaxPost=(url, params={})=>{
	let {data={},method='POST',needToken=true,needLoading=true,needCode=false,json=false}=params;
	return ajax (url, data,method,needToken, needLoading, needCode,json)
}
const ajaxDel=(url, params={})=>{
	let {data={},method='DELETE',needToken=true,needLoading=true,needCode=false,json=false}=params;
	return ajax (url, data,method,needToken, needLoading, needCode,json)
}
const uploadFile = (file,fileType='image') => {
	return new Promise((resolve, reject) => {
		let flag=true,url='/dl/base/upload';
		//#ifdef H5
			flag=false,url='/dl/base/h5Upload';
		//#endif
		getAjaxHeader(flag).then(header=>{
			uni.uploadFile({
				url: host + url,
				filePath: file,
				fileType,//image/video/audio
				name: 'file',
				header,
				success(_res) {
					requestBack(_res.data).then(data=>{
						resolve(data.fileName)
					},reject)
				},
				fail(err) {
					showToast("未知错误，请刷新重试！");
					reject("uploadError");
				}
			})
		},reject)
	})
}
const queryString=(scene)=>{
	let arrPara = decodeURIComponent(scene).replace('\?','').split("&");
	let arr = [];
	let results={};
	for (let i in arrPara) {
		arr = arrPara[i].split("=");
		results[arr[0]]=arr[1]
	}
	return results;
};

const keep2Dec = (num) => {
	let result = '';
	try {
		result = Number(num).toFixed(2)
	} catch (e) {
		result='0.00'
	}
	return isNaN(result)?'0.00':result
}


const checkInput=(input,$scope)=>{
	let {form} = input;
	$scope&&$scope.$set(input, 'checked', '');
	if (form.require) {
		if (!checkFn.noEmpty(input.value)) {
			$scope&&showToast(input.errTips || input.placeholder);
			$scope&&$scope.$set(input, 'checked', 'wrong');
			return false;
		}
	}
	if (form.checkFn && form.checkFn != 'noEmpty' && input.value!=='') {
		let checked = checkFn[form.checkFn].call(this, input.value);
		if (!checked) {
			$scope&&showToast(input.errTips || input.placeholder);
			$scope&&$scope.$set(input, 'checked', 'wrong');
			return false;
		}
	}
	return true;
}

const notNull=(some)=>{
	let reback=false;
	if(some===0){
		reback=true;
	}else {
		reback=some&&some!=='null'?true:false;
	}
	return reback;
}
const navToPage=(url,redirect=false)=>{
	let fn='navigateTo';
	if(redirect){
		fn='redirectTo';
	}
	if(/(index\/index)|(maintain\/maintain)|(my\/my)|(device\/device)/.test(url)){
		fn='switchTab';
		//switchTab不支持url带参数，如果url带参数，则换成reLaunch
		if(url.indexOf('?')!=-1){
			fn='reLaunch'
		}
		url=url.split('?')[0];
	}
	url&&uni[fn]({
		url
	})
}

const callPhone=(phoneNumber)=>{
	phoneNumber&&uni.makePhoneCall({
		phoneNumber
	});
}
const copySome=(some)=>{
	uni.setClipboardData({
	    data: some
	});
}
const joinLogin=(url)=>{
	loginReback.isShow=false;
	navToPage('/pages/login/login?url='+encodeURIComponent(url))
}
const toLogin=(url,{isShowDialog=true,msg='请先登录'})=>{
	if(isShowDialog){
		if(!loginReback.isShow){
			loginReback.isShow=true;
			showDialog(msg,{
				showCancel : false,
				confirmText : "立即登录",
				ok_cb:()=>{
					joinLogin(url)
				},
				no_cb:()=>{
					loginReback.isShow=false;
				}
			})
		}
		
	}else{
		joinLogin(url)
	}
	
}
const loadImg = (src) => {
	return new Promise((resolve, reject) => {
		uni.getImageInfo({
			src,
			success(res) {
				resolve(res);
			},
			fail(err) {
				showToast("获得图片尺寸失败，请刷新重试！");
				reject('getImgInfoFail');
			}
		})
	})
}
let fillAryNum=(num)=>{
	// return new Array(num).fill(1).map((v,i)=>(i+1+'').padStart(2,'0'))
	return new Array(num).fill(1).map((v,i)=>i+1)
};
const DateUtil={
	d28:fillAryNum(28),
	d29:fillAryNum(29),
	d30:fillAryNum(30),
	d31:fillAryNum(31),
	list:['d31','d28','d31','d30','d31','d30','d31','d31','d30','d31','d30','d31'],
	months:fillAryNum(12),
	isLeapYear(year){
		return year%4==0&&year%100!=0||year%400==0;
	},
	getDaysAry(month,year){
		if(month==1){
			return [...this[`d2${this.isLeapYear(year)?9:8}`]]
		}else{
			return [...this[this.list[month]]]
		}
	}
}
const deepCopy = (obj, cache = [])=>{

  function find (list, f) {
    return list.filter(f)[0]
  }

  // just return if obj is immutable value
  if (obj === null || typeof obj !== 'object') {
    return obj
  }

  // if obj is hit, it is in circular structure
  const hit = find(cache, c => c.original === obj)
  if (hit) {
    return hit.copy
  }

  const copy = Array.isArray(obj) ? [] : {}
  // put the copy into cache at first
  // because we want to refer it in recursive deepCopy
  cache.push({
    original: obj,
    copy
  })

  Object.keys(obj).forEach(key => {
    copy[key] = deepCopy(obj[key], cache)
  })

  return copy
}

const parseDate=(time)=>{
	let value='';
	if(time){
		value=new Date(time).formatDateString('yyyy.mm.dd')
	}
	return value;
}

const parseDateTime=(time,format='yyyy-mm-dd hh:MM')=>{
	let value='';
	if(time){
		value=new Date(time).formatDateString(format)
	}
	return value;
}
const optionTpl=()=>{
	return {opts:[],on:'',value:'',disabled:false}
}
const replaceSerial=(str)=>{
	return str.replace(/\d{1,2}\./,'')
}
/**
 * 自动引入当前文件夹下所有module
 * require.context(directory, useSubdirectories = false, regExp = /^.//);
 * @param {String} directory 读取文件的路径
 * @param {Boolean} directory 匹配文件的正则表达式
 * @param {regExp} regExp 读取文件的路径
 */
const getJsFilesExportModule=(files)=>{
	const modules = files.keys().reduce((modules, modulePath) => {
		const moduleName = modulePath.replace(/^.\/(.*)\.js/, '$1');
		const value = files(modulePath);
		moduleName!='index'&&(modules[moduleName] = value);
		return modules
	}, {})
	return modules;
}
const getRadioValue=(index,form,doEvent=true)=>{
	let item=form[index],value='';
	for(let i=0,len=item.options.length;i<len;i++){
		let option=item.options[i];
		if(option.checked){
			value=option.value;
			if(doEvent){
				item.onChange&&item.onChange(item,value,index,form);
			}
			break;
		}
	}
	return value;
}
const setSerial=(input,opts)=>{
	input.hide=opts.length==0;
	input.options[0].opts=opts;
}

const parseDeviceStatusClass=(status)=>{
	return ['se-blue','se-orange','se-red'][status]
}
const parseDeviceStatusTxt=(status)=>{
	return ['在线','离线','故障'][status]
}
const parseSignal=(status)=>{
	// -1弱，0中，1强
	if(notNull(status)){
		if(status==-1){
			return '弱'
		}else{
			return ['中','强'][status]
		}
	}
	return '--'
};
const parseImageUrl=(url)=>{
	let reg=/$https?\:\/\//
	return reg.test(url)?url:`${host}${url}`
}

export default {
	host,
	loginReback,
	checkFn,
	rejectToLogin,
	getAjaxHeader,
	requestBack,
	ajax,
	ajaxGet,
	ajaxPost,
	ajaxDel,
	uploadFile,
	showDialog,
	queryString,
	prePage,
	refreshPrePage,
	refreshAndReback,
	showToast,
	keep2Dec,
	checkInput,
	notNull,
	navToPage,
	callPhone,
	copySome,
	toLogin,
	loadImg,
	DateUtil,
	deepCopy,
	parseDate,
	parseDateTime,
	optionTpl,
	replaceSerial,
	getJsFilesExportModule,
	getRadioValue,
	setSerial,
	parseDeviceStatusClass,
	parseDeviceStatusTxt,
	parseSignal,
	parseImageUrl
}
